package dup.login.demo.util;

import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class WordUtil {
    @Value(value = "${dup.uploadfile.filepath}")
    private String filePath;
    private static String filePathStatic;

    @Value(value = "${dup.uploadfile.virtualpath}")
    private String virtualPath;
    private static String virtualPathStatic;

    @PostConstruct
    public void init() {
        filePathStatic = filePath;
        virtualPathStatic = virtualPath;
    }

    /**
     * 读Word
     *
     * @param file
     * @throws Exception
     */
    public static List<String> readWord(MultipartFile file) throws Exception {
        String textFileName = file.getOriginalFilename();
        List<String> wordList = new ArrayList<>();
        try {
            if (textFileName.endsWith(".doc")) { //判断文件格式
                InputStream fis = file.getInputStream();
                WordExtractor wordExtractor = new WordExtractor(fis);//使用HWPF组件中WordExtractor类从Word文档中提取文本或段落
                for (String words : wordExtractor.getParagraphText()) {//获取段落内容
                    if (!words.trim().isEmpty()) {
                        wordList.add(words.trim());
                    }
                }
                fis.close();
            }
            if (textFileName.endsWith(".docx")) {
                String fileName = UUID.randomUUID() + ".docx";
                String path = filePathStatic + "/" + fileName;
                File uFile = new File(path);//创建一个临时文件
                if (!uFile.exists()) {
                    uFile.createNewFile();
                }
                FileCopyUtils.copy(file.getBytes(), uFile);//复制文件内容
                OPCPackage opcPackage = POIXMLDocument.openPackage(path);//包含所有POI OOXML文档类的通用功能，打开一个文件包。
                XWPFDocument document = new XWPFDocument(opcPackage);//使用XWPF组件XWPFDocument类获取文档内容
                List<XWPFParagraph> paras = document.getParagraphs();
                for (XWPFParagraph paragraph : paras) {
                    String words = paragraph.getText();
                    if (!words.isEmpty()) {
                        wordList.add(words);
                    }
                }
                uFile.delete();
            }
        } catch (Exception e) {
            throw new Exception("读取Word文档失败!");
        }
        return wordList;
    }

    /**
     * 写Word
     *
     * @param wordDataMap
     * @throws Exception
     */
    public static String writeWord(Map<String, Object> wordDataMap, String templateName) throws Exception {
        //template
        if (!wordDataMap.containsKey("parametersMap")) {
            throw new Exception("数据源parametersMap缺失!");
        }
        String path = filePathStatic + "/template/" + templateName + ".docx";
        File file = new File(path);
        if (file.exists()) {
            FileOutputStream fos = null;
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
                WordTemplate template = new WordTemplate(fileInputStream);
                // 替换数据
                template.replaceDocument(wordDataMap);
                // 生成文件
                String fileName = UUID.randomUUID() + ".docx";
                String newpath = filePathStatic + "/tempfile/" + fileName;
                File outputFile = new File(newpath);
                fos = new FileOutputStream(outputFile);
                template.getDocument().write(fos);
                return virtualPathStatic + "/tempfile/" + fileName;
            } catch (Exception e) {
                throw new Exception("生成模板文档错误!");
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        // e.printStackTrace();
                    }
                }
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        // e.printStackTrace();
                    }
                }
            }
        }
        throw new Exception("模板文档不存在!");
    }

    private String getDate() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateFormat = simpleDateFormat.format(date);
        return dateFormat;
    }
}
